from django import forms
from django.core import validators
from .models import User
from schools.models import School
from courses.models import Course


# 把某个字段所有的错误信息放在一个列表中
class ErrorForm(forms.ModelForm):
    def get_errors(self):
        errors = self.errors.get_json_data()
        new_errors = []
        for key, message_dicts in errors.items():
            messages = []
            for message in message_dicts:
                messages.append(message['message'])
            new_errors[key] = messages
        return new_errors


# 登录表单验证
class LoginForm(forms.Form):
    phone = forms.CharField(max_length=20, label='手机号码', widget=forms.TextInput)
    password = forms.CharField(max_length=20, min_length=5, label='密码', widget=forms.PasswordInput)
    remember = forms.IntegerField(required=False)


# 注册表单验证
class RegisterForm(ErrorForm):
    password_repeat = forms.CharField(max_length=20, min_length=5, label='重复密码', widget=forms.PasswordInput)

    def clean(self):
        cleaned_data = super().clean()
        # 对两次输入的密码是否一致进行校验
        pwd1 = cleaned_data.get('css_password')
        pwd2 = cleaned_data.get('password_repeat')
        if pwd1 != pwd2:
            raise forms.ValidationError('两次密码输入不一致！')

    class Meta:
        model = User
        exclude = ['css_time']


# 用户个人信息表单
class EditUserForm(ErrorForm):
    password_new = forms.CharField(max_length=20, min_length=5, label='新密码', widget=forms.PasswordInput)
    # 重写联系电话field去掉唯一性的检验
    css_phone = forms.CharField(validators=[validators.RegexValidator(r"1[345678]\d{9}", message='请输入正确格式的手机号码！')],
                                label='联系电话', widget=forms.TextInput)

    class Meta:
        model = User
        exclude = ['css_time', 'css_phone']


# 学校信息表单验证
class EditSchoolForm(ErrorForm):
    password_new = forms.CharField(max_length=20, min_length=5, label='新密码', widget=forms.PasswordInput)
    # 重写联系电话field去掉唯一性的检验
    css_phone = forms.CharField(validators=[validators.RegexValidator(r"1[345678]\d{9}", message='请输入正确格式的手机号码！')],
                                label='联系电话', widget=forms.TextInput)

    class Meta:
        model = School
        exclude = ['css_time', 'css_role', 'css_phone']


# 学生可选课程列表元素表单校验
class SelectListForm(ErrorForm):

    class Meta:
        model = Course
        fields = ['css_image', 'css_name', 'css_num', 'css_max_num', 'css_teacher']
